// 持仓管理页面
import React from 'react';
import { connect } from 'dva';
import { ContentPackage, DATA_ENTRY, AdvancedSearch, codeType } from '../../../../comps';
import moment from 'moment';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Menu, Tooltip } from 'antd';
import SecurityManage from './securityManage';
import SecurityUnfreeze from './securityUnfreeze';
import investmentTypeData from '../../../../utils/enumeratedValues/investmentType';
import { isTestRole, isZiGuanEvir } from '../../../../utils/commonFunc';
import dictionaryConfig from '../../../../utils/dictionaryConfig';

@Form.create()
class PositionManage extends React.Component {
  state = {
    currentPage: 1, // 当前页码
    pageSize: 10, // 一页数量
    total: 0, // 数据总数
    isReset: false, // 标记是否点击了“重置”后未重新查询
    queryItems: {
      // 存储最新的查询条件
      dataDt: moment().format('YYYYMMDD'),
      userId: isZiGuanEvir() ? isZiGuanEvir()['iv-user'] : localStorage.getItem('antd-pro-userId'),
    },
    columns: [], // 表格列
    dataSource: [], // 表格数据
    total2: [],
    columns2: [],
    dataSource2: [],
    selMenuItem: '1', // teb默认选中
    buttonOk: true,
    falg: isTestRole(), //是否是测试专用角色
  };

  //初始化函数
  componentDidMount() {
    this.props.dispatch({
      type: 'positionManageM/getManageList',
      payload: {
        dataDt: moment().format('YYYYMMDD'),
        userId: isZiGuanEvir() ? isZiGuanEvir()['iv-user'] : localStorage.getItem('antd-pro-userId'),
        page: 1,
        pageSize: 10,
      },
      callback: (data) => {
        if (data && data.dataSource.length) {
          data.dataSource.map((item, key) => {
            item.key = key;
          });
          this.setState({
            columns: data.columns,
            dataSource: data.dataSource,
            total: data.pageInfo.total,
          });
        } else {
          this.setState({
            dataSource: [],
            columns: [],
            total: 0,
            currentPage: 1,
            numInPage: 10,
          });
        }
      },
    });
    this.props.dispatch({
      type: 'roleModel/Search',
      payload: {},
      callback: (res) => {
        if (res) {
          let result = res.filter((i) => i.roleId == localStorage.getItem('antd-pro-userId'));
          if (result && result.length != 0 && result[0].common) {
            this.setState({ falg: true });
          }
        }
      },
    });
  }

  //获取表格数据
  getList = () => {
    const { queryItems, currentPage, pageSize, selMenuItem } = this.state;
    if (selMenuItem == '1') {
      this.props.dispatch({
        type: 'positionManageM/getManageList',
        payload: {
          ...queryItems,
          page: currentPage,
          pageSize: pageSize,
        },
        callback: (data) => {
          if (data && data.dataSource.length) {
            data.dataSource.map((item, key) => {
              item.key = key;
            });
            this.setState({
              columns: data.columns,
              dataSource: data.dataSource,
              total: data.pageInfo.total,
            });
          } else {
            this.setState({
              dataSource: [],
              columns: [],
              total: 0,
              currentPage: 1,
              numInPage: 10,
            });
          }
        },
      });
    } else {
      this.props.dispatch({
        type: 'positionManageM/getUnfreezeList',
        payload: {
          ...queryItems,
          page: currentPage,
          pageSize: pageSize,
        },
        callback: (data) => {
          if (data && data.dataSource.length) {
            this.setState({
              columns2: data.columns,
              dataSource2: data.dataSource,
              total: data.pageInfo.total,
            });
          } else {
            this.setState({
              dataSource2: [],
              columns2: [],
              total: 0,
              currentPage: 1,
              numInPage: 10,
            });
          }
        },
      });
    }
  };

  // 响应查询
  onQuery = (query) => {
    // 日期格式转换
    query.dataDt = query.dataDt ? query.dataDt.format('YYYYMMDD') : '';
    // 组合默认为空数组
    query.fundId = query.fundId ? query.fundId : [];
    let queryItems = {
      ...query,
      userId: isZiGuanEvir() ? isZiGuanEvir()['iv-user'] : localStorage.getItem('antd-pro-userId'),
    };
    this.securityManage.onRef();
    this.setState(
      {
        queryItems: queryItems,
        isReset: false,
        dataSource: [],
        currentPage: 1, // 当前页码
      },
      () => this.getList(),
    );
  };

  // 响应重置
  onClear = () => {
    this.setState({ isReset: true, currentPage: 1, pageSize: 10 });
    this.securityManage.onRef();
  };
  //teb切换响应
  tebOnchange = (val) => {
    this.setState(
      {
        selMenuItem: val.key,
        currentPage: 1,
      },
      () => this.getList(),
    );
  };
  //表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    if (this.state.isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this,
        this.setState({
          isReset: false,
        });
      return;
    }
    this.setState(
      {
        dataSource: [],
        currentPage: current,
        pageSize: pageSize,
      },
      () => {
        this.getList();
      },
    );
  };
  render() {
    const { selMenuItem, columns, columns2, dataSource, dataSource2, total, currentPage, pageSize, queryItems, buttonOk, falg } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'dataDt',
          title: '日期',
          type: DATA_ENTRY.SINGLEDATE,
          initialValue: moment(),
        },
        {
          dataIndex: 'fundId',
          title: '产品组合',
          multiple: true,
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          treeCheckable: isZiGuanEvir() ? true : false,
        },
        {
          dataIndex: 'tradingCode',
          title: '证券代码',
          type: DATA_ENTRY.SECURITIESCODE,
          codeType: codeType.positioned,
        },
        {
          dataIndex: 'investmentType',
          title: '投资类型',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          dataSource: investmentTypeData,
        },
        {
          dataIndex: 'securityType',
          title: '资产类型',
          type: DATA_ENTRY.TREESELECT,
          allowClear: true,
          dataSource: dictionaryConfig.holdTypeTree,
        },
      ],
      onQuery: (e) => {
        //点击查询按钮
        this.onQuery(e);
      },

      onClear: () => {
        //点击重置按钮
        this.onClear();
      },
    };

    return (
      <ContentPackage
        title='持仓管理'
        contentHtml={
          <div>
            <AdvancedSearch {...searchProps} />
            <div style={{ marginTop: '10px' }}>
              <Menu
                onClick={(val) => {
                  this.tebOnchange(val);
                }}
                defaultSelectedKeys={[selMenuItem]}
                mode='horizontal'
              >
                <Menu.Item key='1'>
                  证券管理
                  <Tooltip
                    title={
                      <div>
                        <div>不支持资产类型为：回购、港股通、存款、债券借贷的调仓；</div>
                        <div>非标调仓需要分别设置“净价”和“全价”；</div>
                        <div>资产类型为期货的，填写的“价格”中不含有合约乘数；</div>
                        <div>资产类型为期权的，填写的“价格”中含有合约乘数。</div>
                      </div>
                    }
                  >
                    <QuestionCircleOutlined style={{ marginLeft: '5px' }} />
                  </Tooltip>
                </Menu.Item>
                {falg && <Menu.Item key='2'>证券冻结解冻查询</Menu.Item>}
              </Menu>
            </div>
            {selMenuItem == 1 && (
              <div>
                <SecurityManage
                  columns={columns}
                  dataSource={dataSource}
                  total={total}
                  currentPage={currentPage}
                  pageSize={pageSize}
                  queryItems={queryItems}
                  handleTableChange={this.handleTableChange}
                  query={this.getList}
                  flag={falg}
                  onRef={(ref) => {
                    this.securityManage = ref;
                  }}
                />
              </div>
            )}
            {selMenuItem == 2 && (
              <div>
                <SecurityUnfreeze
                  columns={columns2}
                  dataSource={dataSource2}
                  total={total}
                  currentPage={currentPage}
                  pageSize={pageSize}
                  queryItems={queryItems}
                  handleTableChange={this.handleTableChange}
                  query={this.getList}
                  onRef={(ref) => {
                    this.securityManage = ref;
                  }}
                />
              </div>
            )}
          </div>
        }
      />
    );
  }
}

export default connect(({ positionManage }) => ({ positionManage }))(PositionManage);
